package com.jy.appmarket.activity;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.prototypes.CardSection;
import it.gmariotti.cardslib.library.prototypes.SectionedCardAdapter;
import it.gmariotti.cardslib.library.view.CardListView;
import it.gmariotti.cardslib.library.view.PullToRefreshListView.RefreshingListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.ActionBar;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;

import com.jy.app.market.idata.card.CardApk;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.cards.ApkUICard;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.EssentialNetEngine;
import com.jy.appmarket.network.engine.cachestrategy.CacheStrategy;
import com.jy.appmarket.network.resultdata.EssentialResultData;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.ActivateStatistics;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.Prefs;
import com.jy.appmarket.utils.Settings;
import com.jy.appmarket.view.LoadingView;
import com.jy.appmarket.view.LoadingView.OnClickListener;
import com.jy.appmarket.widget.essential.PhoneEssentialWidgetProvider;
import com.rad.statistics.android.StatisticsAgent;
import com.umeng.analytics.MobclickAgent;

public class PhoneEssentialActivity extends DownloadActivity implements NetTaskListener,
		OnClickListener, RefreshingListener {

	private static final String TAG = "PhoneEssentialActivity";

	public static final String COME_FROM = "come_from";
	public static final int FROM_NOTIFICATION = 1;
	public static final int FROM_WIDGET = 2;
	public static final int FROM_FAVOR = 3;

	private CardListView mListview;
	private CardArrayAdapter mCardsAdapter;
	private SectionedCardAdapter mSectionAdapter;
	private ArrayList<Card> mCardsArray = new ArrayList<Card>();
	private NetTask mNetTask;
	private NetTask mStaticsNetTask;

	private LoadingView mLoadingView;
	// private long mDataVersion;
	// private String mSource;
	private List<CardApk> mEssentials;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_phone_essential);
		getExtraData();
		initTitle();
		initLoadingView();
		initListView();
		startGetData();
		ActivateStatistics.ActivateFrom(this, this.getClass().getSimpleName());
	}

	private void getExtraData() {
		int comeFrom = getIntent().getIntExtra(COME_FROM, 3);
		if (comeFrom == FROM_NOTIFICATION) {
			// LogUtil.i(TAG, "---------->notification is open!");
			Settings.WriteIsOpen(this, true);
		}

		StatisticsAgent.onEvent(getApplicationContext(), "enterphoneessential");
	}

	private void initListView() {
		mListview = findViewById(R.id.essential_listview);
		mListview.setEmptyView(mLoadingView);
		mListview.needToRefreshOnFooter(false);
		mListview.needToRefreshOnHeader(false);
		mListview.setRefreshListener(this);
		mListview.setVisibility(View.GONE);
	}

	private void initLoadingView() {
		mLoadingView = findViewById(R.id.loading_view_layout);
		mLoadingView.setOnClickListener(this);
		mLoadingView.showWaitView(getString(R.string.loading_wait));
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle(R.string.app_requisite);
		actionBar.setIcon(R.drawable.title_logo);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			goBack();
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void startGetData() {
		mLoadingView.showWaitView(R.string.ptr1_loading_wait);
		EssentialNetEngine engine = new EssentialNetEngine(this);
		engine.setCacheStrategy(new CacheStrategy(true, CacheStrategy.THREE_HOUR));
		mNetTask = new NetTask(this, engine, 0);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mNetTask != null) {
			mNetTask.cancel();
			mNetTask.setListener(null);
			mNetTask = null;
		}
		if (mStaticsNetTask != null) {
			mStaticsNetTask.cancel();
			mStaticsNetTask.setListener(null);
			mStaticsNetTask = null;
		}

		Prefs.setEnterNecessariesWidget(this, true);
		Intent it = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
		AppWidgetManager am = AppWidgetManager.getInstance(this);
		ComponentName cn = new ComponentName(this, PhoneEssentialWidgetProvider.class);
		int[] ids = am.getAppWidgetIds(cn);
		if (ids != null && ids.length != 0) {
			Bundle extra = new Bundle();
			extra.putIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
			it.setComponent(cn);
			it.putExtras(extra);
			sendBroadcast(it);
		} else {
			LogUtil.d(TAG, "no widget to update necessaries");
		}
	}

	private void createAdapter(Map<String, List<CardApk>> essentials) {
		int count = 0;
		List<CardSection> sections = new ArrayList<CardSection>();
		mEssentials = new ArrayList<CardApk>();
		for (String title : essentials.keySet()) {
			sections.add(new CardSection(count, title));
			List<CardApk> list = essentials.get(title);
			for (int i = 0; i < list.size(); i++) {
				CardApk apk = list.get(i);
				if (TextUtils.isEmpty(apk.getApk().getPackageName())) {
					continue;
				}
				ApkUICard uicard = new ApkUICard(this, apk);
				uicard.setApkSource(new ApkSource("essential", count + i, null));
				uicard.setListView(mListview);
				addFileListener(uicard);
				mCardsArray.add(uicard);
				mEssentials.add(apk);
				count++;
			}
//			count += list.size();
		}
		mCardsAdapter = new CardArrayAdapter(this, mCardsArray);
		mCardsAdapter.setInnerViewTypeCount(100);
		mSectionAdapter = new SectionedCardAdapter(this, mCardsAdapter);
		CardSection[] dummy = new CardSection[sections.size()];
		mSectionAdapter.setCardSections(sections.toArray(dummy));
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		if (tag == 0) {
			EssentialResultData resultData = (EssentialResultData) engine.getResultData();
			if (!resultData.isOK()) {
				mLoadingView.showErrorView(R.string.load_failed_retry);
			} else {
				Map<String, List<CardApk>> essentials = resultData.getEssentials();
				if (essentials == null || essentials.size() == 0) {
					mLoadingView.showErrorView(R.string.no_data);
				} else {
					createAdapter(essentials);
					mListview.setExternalAdapter(mSectionAdapter, mCardsAdapter);
					mListview.setVisibility(View.VISIBLE);
					mLoadingView.setVisibility(View.GONE);
				}
			}
		}
	}

	@Override
	public void onTaskRunError(int tag) {
		if (tag == 0) {
			mLoadingView.showErrorView(getString(R.string.ptrl_refresh_fail));
		}
	}

	@Override
	public void onTaskRunCanceled(int tag) {

	}

	private void goBack() {
		AppMarketApplication app = (AppMarketApplication) getApplication();
		if (app.isAppRunning()) {
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.setClass(this, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			startActivity(intent);
		} else {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
		}
		finish();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onLoadingViewClick(View view) {
		startGetData();
	}

	@Override
	public void onHeaderRefreshing() {
		// nothing todo
	}

	@Override
	public void onFooterRefreshing() {
		// nothing todo
	}

//	private class EssentialSectionAdapter extends SectionedCardAdapter {
//
//		public EssentialSectionAdapter(Context context, CardArrayAdapter cardArrayAdapter) {
//			super(context, R.layout.essential_section_layout, cardArrayAdapter);
//		}
//
//		@Override
//		protected View getSectionView(int position, View view, ViewGroup parent) {
//			CardSection section = (CardSection) getCardSections().get(position);
//			TextView title = (TextView) view.findViewById(R.id.essential_section_title);
//			title.setText(section.getTitle());
//			return view;
//		}
//	}

}
